package main

import (
	"fmt"
	"github.com/gorilla/websocket"
	"net/http"
)

var upgrader = websocket.Upgrader{
	// 允许跨域
	CheckOrigin: func(r *http.Request) bool {
		return true
	},
}

func main() {
	http.HandleFunc("/ws", wsHandle)
	http.ListenAndServe("127.0.0.1:8888", nil)
}

func wsHandle(writer http.ResponseWriter, request *http.Request) {
	conn, err := upgrader.Upgrade(writer, request, nil)
	if err != nil {
		fmt.Println("upgrade error.", err)
		return
	}
	defer conn.Close()

	for true {
		// 读消息
		messageType, data, err := conn.ReadMessage()
		if err != nil {
			fmt.Println("read message error.", err)
			break
		}

		fmt.Println("read message = ", string(data))
		// 响应消息
		if err = conn.WriteMessage(messageType, data); err != nil {
			fmt.Println("write message error.", err)
		}
	}
}
